package com.wcsy.myblog.service.serviceImpl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wcsy.myblog.dao.UserMapper;
import com.wcsy.myblog.entity.JsonResult;
import com.wcsy.myblog.entity.User;
import com.wcsy.myblog.service.IUserService;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    HttpSession session;
    @Autowired
    JavaMailSenderImpl javaMailSender;
    @Autowired
    HttpServletResponse response;
    @Autowired
    NumServiceImpl numService;


    @Override
    public void insertlist(User user) throws Exception {
        String getfilter = numService.getfilter(user.getUserName());
     if (!getfilter.equals(user.getUserName())){
         System.out.println("请勿输入敏感词汇");
         return;
     }
//        String page = numService.getfile(file);
        String[] arr ={"/img/q1.jpg","/img/q2.jpg","/img/q3.jpg","/img/q4.jpg","/img/q5.jpg","/img/q6.jpg","/img/q7.jpg","/img/timg.jpg"};
        Random random = new Random();
        int i = random.nextInt(arr.length);
        user.setUserImg(arr[i]);
            //根据手机号查询用户
            User ph_number = userMapper.selectOne(new QueryWrapper<User>().eq("ph_number", user.getPhNumber()));
            //根据用户名查询用户
            User user_name = userMapper.selectOne(new QueryWrapper<User>().eq("user_name", user.getUserName()));
            //如果用户为null 说明手机号未被注册
            if (ph_number == null && user_name == null) {
                String pswd = new SimpleHash("md5",user.getPassword(), ByteSource.Util.bytes(user.getUserName()),5).toString();
                user.setPassword(pswd);
                user.setUserAuthority("");
                user.setUserAttention(0L);
                user.setUserFan(0L);
                user.setUserIncome(0);
                user.setUserBalance(0);
                user.setUserLike(0L);
                user.setUserComment(0L);
                user.setNoLike(0l);
                user.setNoAnnouncement(0L);
                userMapper.Userinsert(user);
            }
    }
    /**
     * 图片验证码
     * */
    public void createcode() throws IOException {

        Random random = new Random();
        //定义图片的宽和高
        int width = 80;
        int height = 35;
        //定义字体大小
        int fontSize = 20;
        //创建缓存图片（保存到内库）
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        //获得图片的绘图对象g
        Graphics g = image.getGraphics();
        //设置背景颜色
        g.setColor(Color.GRAY);
        //填充背景颜色
        g.fillRect(0, 0, width, height);
        //设置字体
        g.setFont(new Font("宋体", Font.PLAIN, fontSize));
        //定义保存字母和数字的字符串
        String str = "abcdefghijklmnopqrstuvwxyz1234567890";
        //定义颜色的数组
        Color[] colors = {Color.BLACK, Color.BLUE, Color.CYAN,
                Color.GREEN, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.YELLOW};
        //连接4个字母或数字
        StringBuilder stringBuilder = new StringBuilder();
        //随机生成4个字母或数字
        for (int i = 0; i < 4; i++) {
            char ch = str.charAt(random.nextInt(str.length()));
            //随机取验证，将文字绘制到图片上
            g.setColor(colors[random.nextInt(colors.length)]);
            //绘制文字，参数1 文字 参数2 横坐标 参数3 纵坐标
            g.drawString(String.valueOf(ch), fontSize * i + 5, fontSize + 5);
            //绘制随机的线条
            g.setColor(colors[random.nextInt(colors.length)]);
            g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));
            //StringBuilder在进行频繁字符串处理时不会创建新字符串，效率高
            stringBuilder.append(ch);
        }
        System.out.println("验证码：" + stringBuilder.toString());
        //把验证码保存到Session中，Sessio将当前用户的信息保存起来，在用户访问访问的各个程序（页面，控制器）中使用
        session.setAttribute("ImgCode", stringBuilder.toString());
        //设置响应头，让浏览器不缓存图片
        response.addHeader("Cache-Control", "no-cache");
        //将验证码通过流发送给浏览器ImageIO发送图片的工具类 参数1：图片 参数2：格式 参数3:输出流
        ImageIO.write(image, "PNG", response.getOutputStream());
    }
    /**
     * 邮箱验证
     */
    public int mailVer(String mail) throws MessagingException {
        int code =0;
        User user = (User) session.getAttribute("user");
        if (user.getMail().equals(mail)){
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //组装。是否支持多文件
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage,true);
            message.setSubject("验证邮箱");
            Random random = new Random();
            double v = random.nextDouble();
             code = (int) ((v * 9 + 1) * 100000);
            System.out.println("此次生成的验证码为："+code);
            message.setText("<h5>尊敬的用户您好！您本次的验证码为：</h5>"+code+"，请尽快验证！禁止对外泄露",true);
            message.setTo(mail);
            message.setFrom("xiaoxuoffer@163.com");
            javaMailSender.send(mimeMessage);
        }else {
            return 0;
        }
          return code;
    }
    /**
     * @apiNote  生成手机短信验证码
     */
    public int codepel(String tel){
        int coder = (int)((Math.random() * 9 + 1) * 100000);
        System.out.println(coder+"+"+tel);
        String accessKeyId = "LTAI4GBTbE9VhYy97dR11CrA";
        String accessSecret = "sORSM0hOKBigxGGTVbKgxGbqlytoJr";
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        //这里的手机号换成用户输入的手机号
        request.putQueryParameter("PhoneNumbers",tel);
        //短信的签名名称
        request.putQueryParameter("SignName", "模拟博客网站");
        //短信的模板id
        request.putQueryParameter("TemplateCode", "SMS_193246991");
        //这里验证码换成个随机数
        request.putQueryParameter("TemplateParam", "{\"code\":\""+coder+"\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return coder;
            //前端判断用户输入验证码与coder相同，则返回到修改密码页面
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}
